package com.hantanger.weblog.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

public class FileUploadService {

	/**
	 * 返回文件名与字节流对应的map
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws FileUploadException
	 */
	public static Map<String, byte[]> getFileUploadInfo(HttpServletRequest request){
		Map<String, byte[]> fileMap = new HashMap<String, byte[]>();
		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator iterator;
		try {
			iterator = upload.getItemIterator(request);
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				if(StringUtils.isNotBlank(item.getName())){
					fileMap.put(item.getName(), IOUtils.toByteArray(item.openStream()));
					break;
				}
			}
			return fileMap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
